budgetThird = 1;
(async function() {
	let rateparams = {
		username: getUsername,
		budgetYear: localStorage.getItem("year"),
		budgetMonth: localStorage.getItem("month"),
		dept: localStorage.getItem("dept"),
		status: 2,
		chartPage: 70404,
		chartNo: 5
	}
	let lis = '';
	let cllblis = '';
	let tabIndex = 0;
	let Request = new Object();
	Request = GetRequest();
	const type = decodeURI(Request['type'])
	await $.get(
		`${API_URL}getdata`, {
			...rateparams
		},
		function(res) {
			let re = eval("(" + res + ")");
			console.log(re)
			let data = re.items[0].charts[0].data;
			document.querySelector('header .tabbar').innerHTML = '';

			let pthem = '';
			for (const item of data) {
				if (item.key02 === localStorage.getItem('budgetPPID') && (item.key11 !== '1' || item.key16 === '1')) {
					if (item.key01 === localStorage.getItem('budgetPID')) {
						document.querySelector('header .tabbar').innerHTML +=
							`<p data-istree="${item.key16}" class="active" data-id= "${item.key01}">${item.key03}</p>`
					} else {
						document.querySelector('header .tabbar').innerHTML +=
							`<p data-istree="${item.key16}" data-id= "${item.key01}">${item.key03}</p>`
					}
				}
				if (item.key01 === localStorage.getItem('budgetPPID')) {
					pthem = item.key03;
				}
				if (item.key01 === localStorage.getItem('budgetPID')) {
					document.querySelector('.vessel .aside').innerHTML = `
										<div class="title">
											<span  class="third">预算执行/</span>
											<span class="fourth">${pthem}/</span>
											<h4>${item.key03}</h4>
										</div>
										<div class="budget">
											<h3>预算总额</h3>
											<h2>${(item.key04)}<span>万元</span></h2>
										</div>
										<div class="statistics">
											<h4>执行总额</h4>
											<h3>${(item.key06)}<span>万元</span></h3>
										</div>
										<div class="statistics">
											<h4>剩余总额</h4>
											<h3>${(item.key05)}<span>万元</span></h3>
										</div>
										<div class="statistics">
											<h4>执行率</h4>
											<h3>${item.key10}%</h3>
											<div class="progress-bar">
												<div style="width: ${item.key10>100?100: item.key10 }%;" class="progress ${item.key10>100?'over':''}"></div>
											</div>
										</div>`
				}
			}
		}
	)

	function GetRequest() {
		var url = encodeURI(window.location.search); //获取url中"?"符后的字串
		var theRequest = new Object();
		if (url.indexOf("?") != -1) {
			var str = url.substr(1);
			strs = str.split("&");
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}
	tabsInt()

	function tabsInt() {
		console.log(type)
		$.get(
			`${API_URL}getdata`, {
				...rateparams,
				chartPage: 70401,
				chartNo: 20,
				budgetNo: localStorage.getItem("budgetPID"),
			},
			function(res) {
				let re = eval("(" + res + ")");
				console.log(re)
				const data = re.items[0].charts[0].data;
				const tabs = data.map(item =>
					`<p data-cource="${item.key03}" data-type="${item.key02}">${item.key01}</p>`).join(
					'')
				document.querySelector('.main .tabs').innerHTML = tabs;
				document.querySelectorAll('.main .tabs p')[0].classList.add('active')
				getLiCard(data[0])
				for (const [index, tab] of document.querySelectorAll('.vessel .main .tabs p').entries()) {
					tab.addEventListener('click', function() {
						const activeTab = document.querySelector('.vessel .main .tabs p.active');
						activeTab && activeTab.classList.remove('active')
						this.classList.add('active')
						tabIndex = index;
						getLiCard(data[index])
					})
				}
			}
		)
	}

	function getLiCard(urlData) {
		$.get(
			`${API_URL}${urlData.key03}`, {},
			function(res) {
				const re = eval("(" + res + ")");
				const data = re.items[0].charts[0].data;
				if (data.length < 1) {
					return
				}
				let htmls;
				let _data;
				if (urlData.key02 === "预算树状图") {
					_data = data.filter(item => item.key02 === localStorage.getItem('budgetPID'))
					htmls = _data.map(item => {
						let li = `<li data-id= "${item.key01}">
											<div class="title">
												<h3>${item.key03}</h3>`
						if (item.key15 === '1') {
							li += `<a>
												<img data-type='${item.key03}' src="assets/images/departmental-charge/right.svg">
											</a>`
						}
						li += `</div>
											<div><div class="rate">
												<div class="chart">
													<svg>
													<circle cx="35" cy="35" r="32" stroke="#E2E2EA"  stroke-width="2" fill="rgba(255, 255, 255, 0.2)" stroke-linecap="round" />
													<circle cx="35" cy="35" r="32"  stroke="${item.key10 > 100 ? '#F53F3F' : '#0062FF'}" stroke-width="5" fill="none" stroke-dasharray="${Math.PI * 64}" stroke-dashoffset="${Math.PI * 64 * ((100 - item.key10) < 0 ? 0 : (100 - item.key10) / 100)}" stroke-linecap="round" />
													</svg><span>${item.key10}%</span></div><p>执行率</p>
											</div>
											<div class="statistics">
												<h4>预算金额</h4>
												<h3>${item.key04}<span>万元</span></h3>
											</div>
											<div class="statistics">
												<h4>执行金额</h4>
												<h3>${item.key06}<span>万元</span></h3>
											</div>
											<div class="statistics">
												<h4>剩余金额</h4>
												<h3>${item.key05}<span>万元</span></h3>
											</div></div>
										</li>`
						return li
					}).join('')
				} else {
					htmls = data.map(item => `<li data-id="${item.key01}">
						<div class="title">
							<h3>${item.key01}</h3>
							<a>
								<img data-type='${item.key01}' src="assets/images/departmental-charge/right.svg">
							</a>
						</div>
						<div class="statistics">
							<h4>执行金额</h4>
							<h3>${item.key03}<span>万元</span></h3>
						</div>
					</li>`).join('')
				}
				document.querySelector('.vessel .main ul').innerHTML = htmls;
				document.querySelectorAll('.vessel .main ul li')[0].classList.add('active')
				if (urlData.key02 === "预算树状图") {
					localStorage.setItem("budgetID", document.querySelectorAll('.vessel .main ul li')[0]
						.dataset.id)
					localStorage.setItem("budgetText", '')
					getMonPayComplete(urlData.key02, _data[0].key13)
					localStorage.setItem("treeCourse", _data[0].key14)
					lifun(urlData.key02, _data)
				} else {
					localStorage.setItem("budgetText", document.querySelectorAll('.vessel .main ul li')[
						0].dataset.id)
					localStorage.setItem("budgetID", localStorage.getItem("budgetPID"))
					getMonPayComplete(urlData.key02, data[0].key04)
					localStorage.setItem("treeCourse", data[0].key05)
					lifun(urlData.key02, data)
				}

				getratestate()

			}
		)
	}
	const ps = document.querySelectorAll('header .tabbar p');
	for (const p of ps) {
		p.onclick = function() {
			if (this.innerText !== document.querySelector('header .tabbar p.active').innerText) {
				document.querySelector('header .tabbar p.active').classList.remove('active')
				this.classList.add('active');
				localStorage.setItem("budgetPID", this.dataset.id)
				if (this.dataset.istree === '1') {
					window.location.reload()
				} else {
					window.location.href = 'budget-enforcement-fifth.html'
				}
			}
		}
	}


	function lifun(urlType, liData) {
		const liis = document.querySelectorAll('.vessel .main ul li');
		for (const [index, li] of liis.entries()) {
			li.addEventListener('click', function(e) {
				if (urlType === '预算树状图') {
					localStorage.setItem("budgetID", this.dataset.id)
					localStorage.setItem("budgetText", '')
					localStorage.setItem("treeCourse", liData[index].key14)
					localStorage.setItem("treeTotal", liData[index].key17)
					getMonPayComplete(urlType, liData[index].key13)
				} else {
					localStorage.setItem("budgetText", this.dataset.id)
					localStorage.setItem("treeCourse", liData[index].key05)
					localStorage.setItem("treeTotal", liData[index].key06)
					getMonPayComplete(urlType, liData[index].key04)
				}
				if (e.target.tagName === 'IMG') {
					const obj = eval('(' + localStorage.getItem('saveID') + ')')
					localStorage.setItem('saveID', JSON.stringify({
						ppid: obj.ppid,
						pid: obj.pid,
						iid: localStorage.getItem('budgetPID'),
						id: localStorage.getItem('budgetID')
					}))
					if (e.target.dataset.type) {
						window.location.href =
							`budget-enforcement-tree.html?index=${tabIndex}&type=${e.target.dataset.type}`;
					} else {
						localStorage.setItem("budgetPPID", localStorage.getItem('budgetPID'))
						localStorage.setItem("budgetPID", this.dataset.id)
						window.location.href = 'budget-enforcement-fifth.html';
					}
					return
				}
				document.querySelector('.vessel .main ul li.active').classList.remove('active')
				this.classList.add('active');
				getratestate()
			})
		}
	}



	function getratestate() {
		console.log(tabIndex)
		$.get(
			`${API_URL}getdata`, {
				...rateparams,
				chartPage: 70402,
				budgetNo: localStorage.getItem("budgetID"),
				chartNo: 3,
				key01: localStorage.getItem("budgetText")
			},
			function(res) {
				let re = eval("(" + res + ")");
				document.querySelector('.vessel .main .item-detail .state .p').innerHTML = re.items[0]
					.charts[0].data.length > 0 ? re.items[0]
					.charts[0].data[0].key01 : ''
			})
	}
	document.querySelector('.third').onclick = function() {
		window.location.href = 'budget-enforcement-third.html';
	}

	document.querySelector('.fourth').onclick = function() {
		const obj = eval('(' + localStorage.getItem('saveID') + ')')
		localStorage.setItem("budgetPPID", obj.ppid)
		localStorage.setItem("budgetPID", obj.pid)
		window.location.href = 'budget-enforcement-fourth.html';
	}

	//月度到款执行
	function getMonPayComplete(urlType, url) {
		$.get(
			`${API_URL}${url}`, {},
			function(res) {
				let re = eval("(" + res + ")");
				console.log(re)
				const data = re.items[0].charts[0].data;
				if (data.length === 0) {
					if (document.querySelector('#monthlj')) {
						document.querySelector('#monthlj') && document.querySelector('#monthlj').remove()
						document.querySelector('.month').innerHTML += `<div class="nowrap">
										<div class="noData">
											<img src="assets/images/mask/budget-All-IncomingPayment.svg" >
											<p>暂无数据</p>
										</div>
									</div>`
					}
					return
				}
				if (document.querySelector('.nowrap')) {
					document.querySelector('.nowrap').remove();
					document.querySelector('.month').innerHTML += `<div id="monthlj"></div>`
				}
				const legend = re.items[0].charts[0].chart_name.split(' ').splice(2);
				const legendData = legend.map(item => {
					let newIt = item.split('-').splice(1)[0]
					if (newIt.indexOf('{') > -1) {
						newIt = newIt.replace('{', '')
					}
					if (newIt.indexOf('}') > -1) {
						newIt = newIt.replace('}', '')
					}
					return newIt
				})
				const colors = ['#165DFF', '#50CD89', '#7239EA']
				let xData = [];
				for (let i = 0; i < data.length; i++) {
					xData.push(+data[i].key01);
				}
				const Data = [];
				for (let i = 0; i < legendData.length; i++) {
					Data.push({
						name: legendData[i],
						type: legendData[i].indexOf('率') > -1 ? "line" : "bar",
						barWidth: '30%',
						barGap: 0,
						yAxisIndex: legendData[i].indexOf('率') > -1 ? 1 : 0,
						itemStyle: {
							color: legendData.length > 1 ? colors[i] : colors[1],
						},
						data: [],
					})
					for (const item of data) {
						Data[i].data.push(item['key0' + (i + 2)])
					}
				}
				have("monthlj") ? mulitYBar("monthlj", xData, legendData, Data, '月', true, (legendData
					.length > 1)) : "";
			})

	}


	document.querySelector('.vessel .main .item-detail .state div img').onclick = function() {
		document.querySelector(
				'.vessel .main .item-detail .state div .mask-content textarea').value = document
			.querySelector('.vessel .main .item-detail .state .p').innerText
		toggle()
	}


	document.querySelector('.edit .mask-content .btn button.cancle').onclick = function() {
		toggle()
	}

	function toggle() {
		document.querySelector('.edit .mask-position').style.display = document.querySelector(
			'.edit .mask-position').style.display !== 'block' ? 'block' : 'none'
	}

	document.querySelector('.edit .mask-content .btn button.save').onclick = () => {
		$.get(
			`${API_URL}getdata`, {
				...rateparams,
				chartNo: 4,
				chartPage: 70402,
				budgetNo: localStorage.getItem("budgetID"),
				key01: document.querySelector(
					'.vessel .main .item-detail .state div .mask-content textarea').value,
				key02: localStorage.getItem("budgetText")
			},
			function(res) {
				let re = eval("(" + res + ")");
				alert(re.items[0].charts[0].chart_name)
				getratestate()
				toggle()
			})
	}
})()
